import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import router from '@/router'
import { flattenTree, faviconChange, findPath } from '@/utils/common'
import { menuLists } from '@/api/common'
import axios from 'axios'
import useUserStore from '@/store/user'
import useThemeStore from '@/store/theme'
import useSystemStore from '@/store/system'
import useTagStore from '@/store/tags'

nprogress.configure({
  showSpinner: false
})

/**
 * 主题渲染
 * @param to
 */
const rightTheme = async (to) => {
  const themeStore = useThemeStore()

  // 如果跳转到404不需要主题判断
  if (to.name === 'All') return

  // 主题渲染放在路由下为了防止接口异步造成主题延迟渲染
  // 渲染唯一标识，防止每次路由拦重复渲染
  if (!themeStore.themeFlag) {
    // 判断是否开启动态主题渲染，没有开启使用默认主题
    if (themeStore.dynamic) {
      // 模拟接口调用获取数据
      const { data: { data } } = await axios.post('http://nettranstest.dhgylian.com/renter/config/url', { url: window.location.origin })
      const companyConfig = JSON.parse(data.companyConfig)
      let theme = Object.assign(
        { companyName: data.companyName, url: companyConfig.serverUrl },
        companyConfig,
        companyConfig.other
      )

      // 过滤空值
      theme = Object.fromEntries(
        Object.entries(theme).filter(([key, value]) => value !== null && value !== undefined && value !== '')
      )

      themeStore.setTheme(theme)
    }

    faviconChange(themeStore.favicon)
    document.title = themeStore.title

    themeStore.setThemeFlag(true)
  }
}

// VueRouter 4 中可以不写 next 了，默认就是通过状态
router.beforeEach(async (to, from) => {
  nprogress.start()

  try {
    await rightTheme(to)
  } catch (error) {
    console.log('🚀 ~ file: authorize.js ~ line 80 ~ router.beforeEach ~ error', '主题接口错误' + error)
    return {
      name: 'All'
    }
  }

  const userStore = useUserStore()
  // 此路由需要授权
  if (to.meta.requiresAuth) {
    // 请检查是否登录
    if (!userStore.token) {
      // 如果没有，则重定向到登录页面
      return {
        path: '/login',
        // 保存我们所在的位置，以便以后再来
        query: { redirect: to.fullPath }
      }
    }
    const systemStore = useSystemStore()
    // 登录后获取用户信息及权限
    if (!systemStore?.menus.length) {
      // 获取用户信息
      try {
        const { user, nav, btns } = await menuLists()
        // 储存用户信息
        userStore.setUser(user)
        // 储存菜单
        systemStore.setMenus(nav)
        // 储存按钮
        systemStore.setBtns(btns)
        // 删除没有权限的路由 参数1：所有需要鉴权的路由，参数2：拍平路由
        // filterUniqueByPath(router.getRoutes().filter(item => item.meta.requiresAuth), flattenTree(nav))
        // return to.fullPath
      } catch (error) {
        console.log('🚀 ~ file: authorize.js ~ line 64 ~ router.beforeEach ~ error', error)
      }
    }

    // 判断是否有权限
    const toPath = to.matched[to.matched.length - 1].path
    const flag = flattenTree(systemStore.menus).map(item => item.menuPath.toLowerCase()).includes(toPath)
    if (!flag) {
      return {
        name: 'All'
      }
    }

    const tagStore = useTagStore()
    // 处理到达路径 用于缓存, 面包屑
    tagStore.setBreadcrumb(findPath(toPath, systemStore.menus))
  } else {
    // 禁止用户登录状态下跳转至login
    if (userStore.token && to.path === '/login') {
      return {
        path: '/'
      }
    }
  }
})

router.afterEach(() => {
  nprogress.done()
})

// 删除没有权限的路由
// function filterUniqueByPath (arr1, arr2) {
//   arr1.filter(item => !arr2.map(arr2Item => arr2Item.menuPath).includes(item.path)).forEach(item => {
//     router.removeRoute(item.name)
//   })
// }

export default app => { }
